package com.itbaizhan.login.service.impl;

import com.itbaizhan.common.redis.dao.RedisDao;
import com.itbaizhan.common.vo.LivegoodsResult;
import com.itbaizhan.login.service.LoginService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@DubboService
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisDao redisDao;
    @Value("${livegoods.redis.yzm}")
    private String yzmKey;
    @Override
    public LivegoodsResult sendYZM(String phone) {
        if(redisDao.hasKey(yzmKey+":"+phone)){
            return LivegoodsResult.error("验证码有效时间为两分钟，请不要重复发送~");
        }
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i=0 ;i<4;i++){
            int nextInt = random.nextInt(10);
            sb.append(nextInt);
        }
        redisDao.set(yzmKey+":"+phone,sb.toString(),2, TimeUnit.MINUTES);
        System.out.println(sb.toString());
        return LivegoodsResult.ok("发送成功");
    }

    @Override
    public LivegoodsResult login(String username, String password) {
        String yzm = yzmKey+":"+username;
        if(redisDao.hasKey(yzm)){
            String validateCode = redisDao.get(yzm).toString();
            if(validateCode.equals(password)){
                redisDao.del(yzm);
                return  LivegoodsResult.ok("登陆成功");
            }
            return LivegoodsResult.error("验证码错误");
        }
        return LivegoodsResult.error("手机号或验证码错误");
    }
}
